package com.neomanager.admin.web;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;

import com.neomanager.admin.dao.BannerDao;
import com.neomanager.common.dao.CommonDao;
import com.neomanager.login.model.AdminInfo;
import com.util.FileUtil;
import com.util.UtilCommon;

@Controller
@SessionAttributes("adminInfo")
public class MainBannerController
{
	private final Logger logger = Logger.getLogger(this.getClass());
	@Resource(name="BannerDao")
	BannerDao Banner;
	@Resource(name="CommonDao")
	CommonDao Common;
	/**
	 * 배너 목록 화면
	 */
	@RequestMapping(value = "/admin/main_bannermng_list.do", method = RequestMethod.GET)
	public String listMainBannermng(@RequestParam Map<String, Object> commandMap, Model model,
			HttpServletRequest request, HttpServletResponse response)
	{
		logger.info("배너 목록.");

	    HttpSession session = request.getSession();
	    AdminInfo aInfo = (AdminInfo) session.getAttribute( "adminInfo" );
		String id = aInfo.getAdmin_id();
		String menuFile = "../menu/" + id + "_menu.jsp";

		// 현재 페이지
		int page = 1;
		if (commandMap.get("page") != null)
			page = Integer.parseInt(commandMap.get("page").toString());

		// 페이지당 목록 수
		int pageCount = 10;

		// 시작번호
		int startNo = (page - 1) * pageCount;

		commandMap.put("page", page);
		commandMap.put("pageCount", pageCount);
		commandMap.put("banner_sort", "2"); // 배너 목록 가져오기
		ArrayList<Map<String, Object>> listMap = Banner.selectBannerInfo(commandMap);

		// 총 갯수
		int totalCount = 0;
		if ( listMap != null && listMap.size() > 0 )
		{
			Map<String, Object> rs = listMap.get(0);
			totalCount = Integer.parseInt( rs.get("TOTALCOUNT").toString() );
		}

		// 페이징 처리
		if (totalCount > 0)
		{
			UtilCommon util = new UtilCommon();
			// 총게시물수, 페이지당 목록수, 현재페이지, 블럭당 나타낼 페이지 수
			util.setPage(totalCount, pageCount, page, 10);
			commandMap.put("totalCount", totalCount);
			commandMap.put("totalPage", util.getTotalPage());
			commandMap.put("startPage", util.getStartPage());
			commandMap.put("endPage", util.getEndPage());
			commandMap.put("startNo", startNo);
		}

		model.addAttribute("commandMap", commandMap);
		model.addAttribute("menuinclude", menuFile);
		model.addAttribute("listMap", listMap);

		return "admin/main_bannermng_list";
	}

	/**
	 * 배너 등록 화면
	 */
	@RequestMapping(value = "/admin/main_bannermng_write.do", method = RequestMethod.GET)
	public String writeMainBannermng(@RequestParam Map<String, Object> commandMap, Model model,
			HttpServletRequest request, HttpServletResponse response)
	{
		logger.info("배너 등록");
		HttpSession session = request.getSession();
		AdminInfo aInfo = (AdminInfo) session.getAttribute( "adminInfo" );
		String id = aInfo.getAdmin_id();
		String menuFile = "../menu/" + id + "_menu.jsp";

		model.addAttribute("menuinclude", menuFile);

		return "admin/main_bannermng_write";
	}

	/**
	 * 배너 수정 화면
	 */
	@RequestMapping(value = "/admin/main_bannermng_edit.do", method = RequestMethod.GET)
	public String editMainBannermng(@RequestParam Map<String, Object> commandMap, Model model,
			HttpServletRequest request, HttpServletResponse response)
	{
		logger.info("배너 수정 화면.");
	    HttpSession session = request.getSession();
	    AdminInfo aInfo = (AdminInfo) session.getAttribute( "adminInfo" );
		String id = aInfo.getAdmin_id();
		String menuFile = "../menu/" + id + "_menu.jsp";

		Map<String, Object> listMap = Banner.selectBannerInfoById(commandMap);

		commandMap.put("file_job_id", "M_banner");
		commandMap.put("file_relate_id", listMap.get("FILE_RELATE_ID"));
		ArrayList<Map<String, Object>> fileListMap = Common.selectFileInfoList(commandMap);

		if (!fileListMap.isEmpty())
		{
			model.addAttribute("fileListMap", fileListMap.get(0));
		}
		
		model.addAttribute("menuinclude", menuFile);
		model.addAttribute("listMap", listMap);

		return "admin/main_bannermng_edit";
	}

	/**
	 * 배너 등록/수정/삭제 처리
	 * @throws IOException 
	 */
	@RequestMapping(value = "/admin/main_bannermng_proc.do", method = RequestMethod.POST)
	public String processMainBannermng(@RequestParam Map<String, Object> commandMap, Model model,
			HttpServletRequest request, HttpServletResponse response) throws IOException
	{
		logger.info("배너 등록/수정/삭제 처리");

		if(commandMap.get("mode").toString().equals("write"))
		{
			//식별 아이디 생성
			String banner_id = "B"+UtilCommon.idMake("");
			String file_relate_id = "F"+UtilCommon.idMake("");
			String file_id = UtilCommon.idMake("");

			// 폴더 파일 저장
			Properties props = new Properties();
			props.load(new java.io.BufferedInputStream( getClass().getClassLoader().getResourceAsStream("config.properties")) );
			String strFilePath = props.getProperty("uploadsDir").trim();

			String banner_img_url = "";
			String pathUrl = "/uploads/M_banner";
			strFilePath = strFilePath + File.separator + "M_banner";
			
			Map<String, Map<String, String>> fileInfoMap = FileUtil.doMultiFileUpLoad(request, strFilePath, pathUrl);

			if (fileInfoMap != null)
			{
			    Iterator<String> iterator = fileInfoMap.keySet().iterator();
			    while (iterator.hasNext())
			    {
			        Map<String, String> fileMap = new HashMap<String, String>();
			        String key = iterator.next();
			        banner_img_url = fileInfoMap.get(key).get("FILEURLPATH").toString() + fileInfoMap.get(key).get("FILERENAME").toString();
			        fileMap = fileInfoMap.get(key);
			        fileMap.put("FILE_JOB_ID", "M_banner");
			        fileMap.put("FILE_RELATE_ID", file_relate_id);
			        fileMap.put("FILE_ID", file_id);

			        Common.processFileUpload(fileMap);
			    }
			}
			
			commandMap.put("banner_img_url", banner_img_url);
			commandMap.put("banner_id", banner_id);
			commandMap.put("file_relate_id", file_relate_id);

			Banner.insertBannerInfo(commandMap);
		}
		else if(commandMap.get("mode").toString().equals("edit"))
		{
		
			//첨부 파일 수정 했을 경우
			if(commandMap.get("attached").toString().equals("Y")){

				String filePath = commandMap.get("file_path").toString() +
									commandMap.get("file_rename").toString();
				FileUtil.doMulitFileDelete(filePath); //첨부파일 삭제
				
				// 폴더 파일 저장
				Properties props = new Properties();
				props.load(new java.io.BufferedInputStream( getClass().getClassLoader().getResourceAsStream("config.properties")) );
				String strFilePath = props.getProperty("uploadsDir").trim();

				String banner_img_url = "";
				String pathUrl = "/uploads/M_banner";
				strFilePath = strFilePath + File.separator + "M_banner";

				Map<String, Map<String, String>> fileInfoMap =  FileUtil.doMultiFileUpLoad(request, strFilePath, pathUrl);

				if (fileInfoMap != null)
				{
				    Iterator<String> iterator = fileInfoMap.keySet().iterator();
				    while (iterator.hasNext())
				    {
				        Map<String, String> fileMap = new HashMap<String, String>();
				        String key = iterator.next();
				        fileMap = fileInfoMap.get(key);
				        banner_img_url = fileInfoMap.get(key).get("FILEURLPATH").toString() + fileInfoMap.get(key).get("FILERENAME").toString();
				        fileMap.put("file_job_id", "M_banner");
				        fileMap.put("file_relate_id", commandMap.get("file_relate_id").toString());

				        commandMap.put("banner_img_url", banner_img_url);
				        
				        Common.updateFileInfo(fileMap);// 첨부 파일 정보 수정
				    }
				}//end if
			}//end if
			
			Banner.updateBannerInfo(commandMap);
		}
		else if(commandMap.get("mode").toString().equals("delete"))
		{
			String filePath = commandMap.get("file_path").toString() +
								commandMap.get("file_rename").toString();
			FileUtil.doMulitFileDelete(filePath); //첨부파일 삭제

			Banner.deleteBannerInfo(commandMap); //배너 정보 삭제
			Common.deleteFileInfo(commandMap); //첨부 파일 정보 삭제
		}

		return "redirect:../admin/main_bannermng_list.do";
	}
}
